<?php

/**
 * 律师模型
 */

namespace app\model\lawyer;

use think\Model;
use think\model\concern\SoftDelete;

class Lawyer extends Model
{
    use SoftDelete;

    // 设置表名 - 使用带前缀的完整表名
    protected $name = 'lawyer';

    // 设置主键
    protected $pk = 'id';

    // 设置软删除字段
    protected $deleteTime = 'delete_time';

    // 设置自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 设置时间字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 设置类型转换
    protected $type = [
        'id' => 'integer',
        'username' => 'string',
        'pwd' => 'string',
        'salt' => 'string',
        'name' => 'string',
        'email' => 'string',
        'mobile' => 'integer',
        'sex' => 'integer',
        'thumb' => 'string',
        'firmid' => 'integer',
        'firm_name' => 'string',
        'type' => 'integer',
        'idcard' => 'string',
        'lawyer_license' => 'string',
        'provinceid' => 'integer',
        'cityid' => 'integer',
        'distid' => 'integer',
        'education' => 'string',
        'honor' => 'string',
        'adept' => 'string',
        'desc' => 'string',
        'entry_time' => 'integer',
        'create_time' => 'integer',
        'update_time' => 'integer',
        'last_login_time' => 'integer',
        'login_num' => 'integer',
        'last_login_ip' => 'string',
        'status' => 'integer',
        'admin_id' => 'integer',
        'can_login' => 'integer',
        'sync_status' => 'integer',
    ];

    /**
     * 关联律所模型
     */
    public function lawfirm()
    {
        return $this->belongsTo('app\model\lawyer\Lawfirm', 'firmid', 'id');
    }

    /**
     * 关联管理员模型
     */
    public function admin()
    {
        return $this->belongsTo('app\model\admin\User\Admin', 'admin_id', 'id');
    }

    /**
     * 关联部门模型（律所对应的部门）
     */
    public function department()
    {
        return $this->belongsTo('app\model\department\Department', 'firmid', 'firm_id');
    }

    /**
     * 获取律师列表（带分页）
     * 
     * @param array $param 查询参数
     * @return array 律师列表和总数
     */
    public static function getList(array $param = [])
    {
        $page = isset($param['page']) ? (int)$param['page'] : 1;
        $limit = isset($param['limit']) ? (int)$param['limit'] : 10;

        // 构建查询条件
        $where = [];
        $where[] = ['l.status', '<>', -1]; // 排除已删除的记录

        // 关键词搜索
        if (!empty($param['keywords'])) {
            $where[] = ['l.name|l.mobile', 'like', '%' . trim($param['keywords']) . '%'];
        }

        // 按状态筛选
        if (isset($param['status']) && $param['status'] !== '') {
            $where[] = ['l.status', '=', $param['status']];
        }

        // 按律所筛选
        if (!empty($param['lawfirm_id'])) {
            $where[] = ['l.firmid', '=', $param['lawfirm_id']];
        }

        // 按类型筛选
        if (isset($param['type']) && $param['type'] !== '') {
            $where[] = ['l.type', '=', $param['type']];
        }

        // 使用原生SQL查询来避免字段歧义
        $prefix = config('database.connections.mysql.prefix');
        $lawyerTable = $prefix . 'lawyer';
        $lawfirmTable = $prefix . 'lawfirm';
        $regionTable = $prefix . 'region';

        // 构建查询SQL，直接关联地区表获取省市区名称
        // 修复：添加 can_login 和 admin_id 字段
        $fieldSql = "l.id, l.username, l.name, l.email, l.mobile, l.sex, l.thumb, l.firmid, lf.title as firm_name, l.type, l.idcard, l.lawyer_license, l.provinceid, l.cityid, l.distid, p.name as province, c.name as city, d.name as district, l.education, l.honor, l.adept, l.desc, l.entry_time, l.create_time, l.update_time, l.last_login_time, l.login_num, l.last_login_ip, l.status, l.can_login, l.admin_id";
        $whereSql = "l.status <> -1";
        $params = [];

        // 关键词搜索
        if (!empty($param['keywords'])) {
            $whereSql .= " AND l.name LIKE :keywords";
            $params['keywords'] = '%' . trim($param['keywords']) . '%';
        }

        // 按状态筛选
        if (isset($param['status']) && $param['status'] !== '') {
            $whereSql .= " AND l.status = :status";
            $params['status'] = $param['status'];
        }

        // 按律所筛选
        if (!empty($param['lawfirm_id'])) {
            $whereSql .= " AND l.firmid = :firmid";
            $params['firmid'] = $param['lawfirm_id'];
        }

        // 按类型筛选
        if (isset($param['type']) && $param['type'] !== '') {
            $whereSql .= " AND l.type = :type";
            $params['type'] = $param['type'];
        }

        // 查询律师列表
        $listSql = "SELECT {$fieldSql} FROM {$lawyerTable} l 
                    LEFT JOIN {$lawfirmTable} lf ON l.firmid = lf.id 
                    LEFT JOIN {$regionTable} p ON l.provinceid = p.id 
                    LEFT JOIN {$regionTable} c ON l.cityid = c.id 
                    LEFT JOIN {$regionTable} d ON l.distid = d.id 
                    WHERE {$whereSql} ORDER BY l.id DESC LIMIT :limit OFFSET :offset";
        $listParams = $params;
        $listParams['limit'] = $limit;
        $listParams['offset'] = ($page - 1) * $limit;

        $list = \think\facade\Db::query($listSql, $listParams);

        // 查询总数
        $countSql = "SELECT COUNT(l.id) as count FROM {$lawyerTable} l LEFT JOIN {$lawfirmTable} lf ON l.firmid = lf.id WHERE {$whereSql}";
        $countResult = \think\facade\Db::query($countSql, $params);
        $count = $countResult[0]['count'];

        return [
            'list' => $list,
            'count' => $count
        ];
    }

    /**
     * 获取单个律师信息
     * 
     * @param int $id 律师ID
     * @return array 律师信息
     */
    public static function getDetail(int $id)
    {
        // 使用原生SQL查询来避免字段歧义
        $prefix = config('database.connections.mysql.prefix');
        $lawyerTable = $prefix . 'lawyer';
        $lawfirmTable = $prefix . 'lawfirm';
        $regionTable = $prefix . 'region';

        // 构建查询SQL，直接关联地区表获取省市区名称
        // 修复：添加 can_login 和 admin_id 字段
        $fieldSql = "l.id, l.username, l.name, l.email, l.mobile, l.sex, l.thumb, l.firmid, lf.title as firm_name, l.type, l.idcard, l.lawyer_license, l.provinceid, l.cityid, l.distid, p.name as province, c.name as city, d.name as district, l.education, l.honor, l.adept, l.desc, l.entry_time, l.create_time, l.update_time, l.last_login_time, l.login_num, l.last_login_ip, l.status, l.can_login, l.admin_id";
        $sql = "SELECT {$fieldSql} FROM {$lawyerTable} l 
                LEFT JOIN {$lawfirmTable} lf ON l.firmid = lf.id 
                LEFT JOIN {$regionTable} p ON l.provinceid = p.id 
                LEFT JOIN {$regionTable} c ON l.cityid = c.id 
                LEFT JOIN {$regionTable} d ON l.distid = d.id 
                WHERE l.id = :id AND l.status <> -1 LIMIT 1";

        $result = \think\facade\Db::query($sql, ['id' => $id]);

        return !empty($result) ? $result[0] : null;
    }

    /**
     * 获取启用的律师列表（用于下拉选择）
     * 
     * @return array 律师列表
     */
    public static function getEnableList()
    {
        // 使用原生SQL查询来避免字段歧义
        $prefix = config('database.connections.mysql.prefix');
        $lawyerTable = $prefix . 'lawyer';
        $lawfirmTable = $prefix . 'lawfirm';
        $regionTable = $prefix . 'region';

        // 构建查询SQL，直接关联地区表获取省市区名称
        // 修复：添加 can_login 和 admin_id 字段
        $fieldSql = "l.id, l.username, l.name, l.email, l.mobile, l.sex, l.thumb, l.firmid, lf.title as firm_name, l.type, l.idcard, l.lawyer_license, l.provinceid, l.cityid, l.distid, p.name as province, c.name as city, d.name as district, l.education, l.honor, l.adept, l.desc, l.entry_time, l.create_time, l.update_time, l.last_login_time, l.login_num, l.last_login_ip, l.status, l.can_login, l.admin_id";
        $sql = "SELECT {$fieldSql} FROM {$lawyerTable} l 
                LEFT JOIN {$lawfirmTable} lf ON l.firmid = lf.id 
                LEFT JOIN {$regionTable} p ON l.provinceid = p.id 
                LEFT JOIN {$regionTable} c ON l.cityid = c.id 
                LEFT JOIN {$regionTable} d ON l.distid = d.id 
                WHERE l.status = 1 ORDER BY l.id DESC";

        return \think\facade\Db::query($sql);
    }

    /**
     * 格式化律师数据
     * 
     * @param array $lawyer 律师数据
     * @return array 格式化后的律师数据
     */
    public static function formatData(array $lawyer)
    {
        // 确保时间字段是整数
        $timeFields = ['create_time', 'update_time', 'entry_time', 'last_login_time'];
        foreach ($timeFields as $field) {
            if (isset($lawyer[$field]) && $lawyer[$field]) {
                $lawyer[$field] = (int)$lawyer[$field];
            } else {
                $lawyer[$field] = 0;
            }
        }

        // 确保数字字段是整数
        $numberFields = ['id', 'sex', 'type', 'status', 'provinceid', 'cityid', 'distid', 'firmid', 'mobile', 'login_num', 'can_login', 'admin_id'];
        foreach ($numberFields as $field) {
            if (isset($lawyer[$field])) {
                $lawyer[$field] = (int)$lawyer[$field];
            }
        }

        // 确保字符串字段
        $stringFields = ['username', 'name', 'email', 'thumb', 'firm_name', 'idcard', 'lawyer_license', 'education', 'honor', 'adept', 'desc', 'last_login_ip', 'province', 'city', 'district'];
        foreach ($stringFields as $field) {
            if (!isset($lawyer[$field]) || $lawyer[$field] === null) {
                $lawyer[$field] = '';
            }
        }

        // 转换状态为中文描述
        switch ($lawyer['status']) {
            case -1:
                $lawyer['status_text'] = '已删除';
                break;
            case 0:
                $lawyer['status_text'] = '禁止登录';
                break;
            case 1:
                $lawyer['status_text'] = '正常';
                break;
            case 2:
                $lawyer['status_text'] = '离职';
                break;
            default:
                $lawyer['status_text'] = '未知';
        }

        // 转换性别为中文描述
        switch ($lawyer['sex']) {
            case 1:
                $lawyer['sex_text'] = '男';
                break;
            case 2:
                $lawyer['sex_text'] = '女';
                break;
            default:
                $lawyer['sex_text'] = '未知';
        }

        // 转换律师类型为中文描述
        switch ($lawyer['type']) {
            case 0:
                $lawyer['type_text'] = '注册律师';
                break;
            case 1:
                $lawyer['type_text'] = '合作律师';
                break;
            default:
                $lawyer['type_text'] = '未知';
        }

        // 组合完整地址
        $lawyer['full_address'] = '';
        if (!empty($lawyer['province'])) {
            $lawyer['full_address'] .= $lawyer['province'];
        }
        if (!empty($lawyer['city'])) {
            $lawyer['full_address'] .= $lawyer['full_address'] ? '-' . $lawyer['city'] : $lawyer['city'];
        }
        if (!empty($lawyer['district'])) {
            $lawyer['full_address'] .= $lawyer['full_address'] ? '-' . $lawyer['district'] : $lawyer['district'];
        }

        return $lawyer;
    }

    /**
     * 排除软删除条件的作用域
     * 
     * @param \think\db\Query $query 查询对象
     * @return void
     */
    public function scopeWithoutSoftDelete($query)
    {
        // 手动禁用ThinkPHP的软删除功能
        $query->removeOption('soft_delete');
    }
}
